using Clear.Api.Tests;

var builder = WebApplication.CreateBuilder(args);

// // 可以嵌入到iframe中
// builder.Services.AddCors(options =>
// {
//     options.AddDefaultPolicy(policy =>
//     {
//         policy
//             .AllowAnyOrigin()
//             .AllowAnyHeader()
//             .AllowAnyMethod();
//     });
// });

builder.Services.AddControllers();

builder.Services.AddMcpServer()
    .WithHttpTransport((option) => { option.Stateless = true; })
    .WithTools<Tools>();

var app = builder.Build();

// app.Use(async (context, next) =>
// {
//     // context.Response.Headers.Add("X-Frame-Options", "ALLOWALL");
//     context.Response.Headers.Add("Content-Security-Policy", "frame-ancestors 'self' *");
//     // context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
//
//     await next();
// });
// app.UseCors();

app.UseHttpsRedirection();
app.MapMcp("/mcp");

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
    {
        var forecast = Enumerable.Range(1, 5).Select(index =>
                new WeatherForecast
                (
                    DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                    Random.Shared.Next(-20, 55),
                    summaries[Random.Shared.Next(summaries.Length)]
                ))
            .ToArray();
        return forecast;
    })
    .WithName("GetWeatherForecast");

app.UseStaticFiles();

app.MapControllers();

// 3. 动态子目录SPA fallback中间件
app.Use(async (context, next) =>
{
    // 排除API请求
    if (context.Request.Path.StartsWithSegments("/api"))
    {
        await next();
        return;
    }

    Console.WriteLine("Handling request: " + context.Request.Path);

    // 尝试获取第一个路径段作为子目录名
    var pathSegments = context.Request.Path.Value?.Split('/') ?? Array.Empty<string>();
    if (pathSegments.Length >= 2 && !string.IsNullOrEmpty(pathSegments[1]))
    {
        var subDirectory = pathSegments[1]; // 提取子目录名（如/abc/xxx → abc）
        var fallbackPath = Path.Combine(subDirectory, "index.html");

        // 检查该子目录下是否存在index.html
        var filePath = Path.Combine(app.Environment.WebRootPath, fallbackPath);
        if (File.Exists(filePath))
        {
            // 返回对应子目录的index.html
            context.Response.ContentType = "text/html";
            await context.Response.SendFileAsync(filePath);
            return;
        }
    }

    // 未匹配到任何子目录SPA，交给后续处理（如返回404）
    await next();
});

// app.MapFallbackToFile("index.html");

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}